<?php

class Groups extends Onecore_Controller
{

    public function __construct()
    {
        parent::__construct();
        $this->load->model("groups_model");
        $this->load->model("typegroups_model");
        $this->_moduleName = utf8_encode("Modulo modulos_model");
        $this->_moduleDescription = utf8_encode("Description") . $this->_moduleName;
        $this->_modelInstance = $this->groups_model;
    }
  
    public function loadList(){
        $cfg = new stdClass();
        $cfg->start = $this->input->get('start');
        $cfg->limit = $this->input->get('limit');
        $cfg->conditions = new stdClass();
        $cfg->conditions->elem_questions_id = $this->input->get('question_id');
        $cfg->conditions->parent = 0;
        $cfg->orderField = 'description';
        $cfg->orderDirection = 'ASC';
        
        $data = $this->_modelInstance->listEntities($cfg);
        $res = array(
            "success" => true,
            "results" => $data['results'],
            "rows" => $data['items']
        );
        $this->layout->printLike(json_encode($res), "json");
    }
    //grilla de usuarios por grupo
    public function registeredUsers() {
        $cfg = $this->config->item('defaultCfg');
        $groups_id = $this->input->get('groups_id');
        $data = $this->_modelInstance->getRegisteredUsers($groups_id);

        $res = array(
            "success" => true,
            "results" => $data['results'],
            "sql" => $data['sql'],
            "rows" => $data['items']
        );
        $this->layout->printLike(json_encode($res), "json");
    }
    public function unregisterUser(){
        $this->load->model("role_group_model");
        $success = false;
        $itemName = $this->role_group_model->getItemName();
        $mensaje = "Error inesperado";
        $errorList = array();
        
        $groups_id = $this->input->post('groups_id');
        $_rols_id = $this->input->post('_rols_id');
        $users_id = $this->input->post('users_id');
        $data = array(
            '_rols_id'=>$_rols_id,
            'users_id'=>$users_id,
            'groups_id'=>$groups_id,
        );
        
        if ($this->role_group_model->del($data, true)) {
            $mensaje = "Inscripcion eliminado en forma existosa";
            $success = true;
        } else {
            $mensaje = "El objeto no puedo ser eliminado. Verifique los siguientes errores.";
            $errorList = array("Error" => $this->role_group_model->getError());
        }
        $data = array(
            'success' => $success,
            "msg" => $mensaje,
            "errors" => $errorList,
        );
        $this->layout->printLike(json_encode($data), "json");
    }
    public function registerUser(){
        $this->load->model("role_group_model");
        $cfg = (object)$this->config->item('defaultCfg');
        $valid = true;
        $success = false;
        $itemName = $this->role_group_model->getItemName();
        $mensaje = $itemName . " inscrito en forma exitosa";
        $errorList = array();
        
        $groups_id = $this->input->post('groups_id');
        $_rols_id = $this->input->post('_rols_id');
        $users_id = $this->input->post('users_id');

        $uid = $this->session->userdata('id_usuario');
        $userEmail = $this->session->userdata('uid');
        
        $this->form_validation->set_rules($this->role_group_model->getValidations());
        $_id = 0;
        $_object = null;

        if ($this->form_validation->run() == FALSE) {
            $mensaje = "Campos inválidos";
            $errorList = $this->form_validation->_error_array;
        } else {
            $data = array(
                "id" => "",
                "data" => array(
                    'groups_id'=>$groups_id,
                    '_rols_id' => $_rols_id,
                    "users_id" => $users_id
                )
            );
            
            if ($this->role_group_model->save($data, false)) {
                $success = true;
            } else {
                $mensaje = "El objeto no pudo ser creado. Verifique los siguientes errores.";
                $errorList = array("Error" => $this->role_group_model->getError());
            }
        }
        $data = array(
            'success' => $success,
            "msg" => $mensaje,
            "errors" => $errorList,
        );
        $this->layout->printLike(json_encode($data), "json");
    }
    //grilla de objetos por grupo
    public function registeredObjects(){
        $cfg = $this->config->item('defaultCfg');
        $groups_id = $this->input->get('groups_id');
        $data = $this->_modelInstance->getRegisteredObjects($groups_id);

        $res = array(
            "success" => true,
            "results" => $data['results'],
            "sql" => $data['sql'],
            "rows" => $data['items']
        );
        $this->layout->printLike(json_encode($res), "json");
    }
    public function registerObject(){
        $this->load->model("role_group_model");
        $this->load->model("objects_model");
        $this->load->model("modules_model");
        $this->load->model("modules_objects_model");
        $this->load->model("type_objects_model");
        $cfg = (object)$this->config->item('defaultCfg');
        $valid = true;
        $success = false;
        $itemName = $this->role_group_model->getItemName();
        $mensaje = $itemName . " inscrito en forma exitosa";
        $errorList = array();
        
        $groups_id = $this->input->post('groups_id');
        $objects_id = $this->input->post('objects_id');
        $dstart = $this->input->post('dstart');
        $dend = $this->input->post('dend');
        $minCorrectAnswers = $this->input->post('minCorrectAnswers');
        $repetitions = $this->input->post('repetitions');

        $selected = $this->input->post('selected');
        $selectedQuestions = $this->input->post('selectedQuestions');
        $nQuestions = $this->input->post('nQuestions');

        $selectedQuestions = json_decode($selectedQuestions);

        $uid = $this->session->userdata('id_usuario');
        $userEmail = $this->session->userdata('uid');
        
        $this->form_validation->set_rules($this->modules_objects_model->getValidations());
        $_id = 0;
        $_object = null;
        $_moduleId = 0;
        $_moduleName = "Módulo de Grupo [$groups_id]";

        if(empty($objects_id)){
            $data = array('success' => false,
                "message" => "Fecha de inicio no puede ser núla",
                "errors" => array("Error" => "Debe seleccionar un objeto válido")
            );
            $this->layout->printLike(json_encode($data), "json");
            return;
        }
        

        //no se definiio inicio
        if(empty($dstart)){
            $data = array('success' => false,
                "message" => "Fecha de inicio no puede ser núla",
                "errors" => array("Error" => "Fecha de inicio no puede ser núla")
            );
            $this->layout->printLike(json_encode($data), "json");
            return;
        }
        //no se definiio termino
        if(empty($dend)){
            $data = array('success' => false,
                "message" => "Fecha de término no puede ser núla",
                "errors" => array("Error" => "Fecha de término no puede ser núla")
                );
            $this->layout->printLike(json_encode($data), "json");
            return;
        }
        //fechas validas
        if(strtotime($dend) <= strtotime($dstart)){
            $data = array('success' => false,
                "message" => "Fecha de término no puede ser núla",
                "errors" => array("Error" => "Fecha de término no puede ser menor o igual a la fecha la de inicio")
                );
            $this->layout->printLike(json_encode($data), "json");
            return;
        }

        //fechas no puede ser menor a la actual
        if(strtotime($dstart) < strtotime(date("Y-m-d"))){
            $data = array('success' => false,
                "message" => "Fecha de término no puede ser núla",
                "errors" => array("Error" => "Fecha de inicio no puede ser menor que la fecha actual")
                );
            $this->layout->printLike(json_encode($data), "json");
            return;
        }

        //no se definiio preguntas a usar
        /*
        if(empty($selectedQuestions) && $nQuestions == ""){
            $data = array(
                'success' => false,
                "message" => "Debe seleccionar si usar preguntas al azar o elegirlas manualmente",
                "errors" => array("Error" => "Debe seleccionar si usar preguntas al azar o elegirlas manualmente")
                );
            $this->layout->printLike(json_encode($data), "json");
            return;   
        }
        */
        //obtenemnos objeto
        $object = $this->objects_model->getByid($objects_id);
        if(empty($object[0])){
            $data = array(
                'success' => false,
                "message" => "El objeto [$objects_id] no existe",
                "errors" => array("Error" => "El objeto [$objects_id] no existe")
            );
            $this->layout->printLike(json_encode($data), "json");
            return;
        }
        $object = $object[0];

        //solo si es tema validamos estoa campos de configuracion de prueba
        if($object->type_objects_id == $cfg->type_object_theme){
            if(empty($minCorrectAnswers) || empty($repetitions) || empty($nQuestions) ){
                $data = array('success' => false,
                    "message" => "Fecha de inicio no puede ser núla",
                    "errors" => array("Error" => "Debe configurar correctamente la prueba.")
                );
                $this->layout->printLike(json_encode($data), "json");
                return;
            }
        }
        


        //obtenemos el tipo objeto
        $typeObject = $this->type_objects_model->getByid($object->type_objects_id);
        if(!empty($typeObject[0])){
            $_moduleName = $typeObject[0]->name;
        }

        //validamos que grupo posea modulo de tipo asociado al objeto
        $modules = $this->modules_model->getBygroups_id($groups_id);
        $module = null;
        foreach ($modules as $m) {
            if($m->type_objects_id == $object->type_objects_id){
                $module = $m;
                break;
            }
        }

        $this->db->trans_begin();

        //si posee modulo usamos este id para crear relacion modules_objects
        if($module!=null){
            $_moduleId = $module->id;
        }
        else{
            //si no posee el modulo lo creamos
            $data = array(
                "id" => "",
                "data" => array(
                    'groups_id'=>$groups_id,
                    'ucreated'=>$userEmail,
                    'type_objects_id' => $object->type_objects_id,
                    "status" => $cfg->object_enabled,
                    "name"=>$_moduleName,
                    "description"=>"Módulo de $_moduleName"
                )
            );
            if ($this->modules_model->save($data, false)) {
                $_moduleId = $this->modules_model->getLastInsertedId();
            } else {
                $data = array(
                    'success' => false,
                    "message" => "Proceso fallo al momento de crear nuevo modulo",
                    "errors" => array("Error" => $this->modules_model->getError())
                );
                $this->db->trans_rollback();
                $this->layout->printLike(json_encode($data), "json");
                return;
            }
        }

        //JSON con configuracion de inscripcion de objeto con modulo
        $config = new stdClass();
        $config->start = $dstart;
        $config->end = $dend;
        $config->test = new stdClass();
        if($selected == "true"){
            $config->test->random = 0;
            $config->test->selectedQuestions = $selectedQuestions;

        }
        else{
            $config->test->random = 1;
            $config->test->nQuestions = $nQuestions;   
        }

        $config->test->minCorrectAnswers = $minCorrectAnswers;
        $config->test->repetitions = $repetitions;


        $data = array(
            "id" => "",
            "data" => array(
                'modules_id'=>$_moduleId,
                'objects_id' => $objects_id,
                'objectversion' => $object->version,
                "config"=>json_encode($config),
            )
        );
        
        if (!$this->modules_objects_model->save($data, false)) {
            $data = array(
                'success' => false,
                "message" => "Proceso fallo al momento de inscribir objeto con modulo [$_moduleId] del Grupo [$groups_id]",
                "errors" => array("Error" => $this->modules_objects_model->getError())
            );
            $this->db->trans_rollback();
            $this->layout->printLike(json_encode($data), "json");        
            return;
        } 
        else{
            $this->db->trans_commit();
        }
        $data = array(
            'success' => true,
            "message" => "Inscripción exitosa",
            "errors" => array(),
        );
        $this->layout->printLike(json_encode($data), "json");
    }
    public function editSubscribedObject(){
        $this->load->model("role_group_model");
        $this->load->model("objects_model");
        $this->load->model("modules_model");
        $this->load->model("modules_objects_model");
        $this->load->model("type_objects_model");
        $cfg = (object)$this->config->item('defaultCfg');
        $valid = true;
        $success = false;
        $itemName = $this->role_group_model->getItemName();
        $mensaje = $itemName . " inscrito en forma exitosa";
        $errorList = array();
        
        $groups_id = $this->input->post('groups_id');
        //$objects_id = $this->input->post('objects_id');
        $dstart = $this->input->post('dstart');
        $dend = $this->input->post('dend');
        $minCorrectAnswers = $this->input->post('minCorrectAnswers');
        $repetitions = $this->input->post('repetitions');
        $objects_id = $this->input->post('objects_id');
        $modules_id = $this->input->post('modules_id');

        $selected = $this->input->post('selected');
        $selectedQuestions = $this->input->post('selectedQuestions');
        $nQuestions = $this->input->post('nQuestions');

        $selectedQuestions = json_decode($selectedQuestions);

        $uid = $this->session->userdata('id_usuario');
        $userEmail = $this->session->userdata('uid');
        
        $this->form_validation->set_rules($this->modules_objects_model->getValidations());
        $_id = 0;
        $_object = null;
        $_moduleId = 0;
        $_moduleName = "Módulo de Grupo [$groups_id]";

        if(empty($objects_id)){
            $data = array('success' => false,
                "message" => "Fecha de inicio no puede ser núla",
                "errors" => array("Error" => "Debe seleccionar un objeto válido")
            );
            $this->layout->printLike(json_encode($data), "json");
            return;
        }
        //no se definiio inicio
        if(empty($dstart)){
            $data = array('success' => false,
                "message" => "Fecha de inicio no puede ser núla",
                "errors" => array("Error" => "Fecha de inicio no puede ser núla")
            );
            $this->layout->printLike(json_encode($data), "json");
            return;
        }
        //no se definiio termino
        if(empty($dend)){
            $data = array('success' => false,
                "message" => "Fecha de término no puede ser núla",
                "errors" => array("Error" => "Fecha de término no puede ser núla")
                );
            $this->layout->printLike(json_encode($data), "json");
            return;
        }
        //fechas validas
        if(strtotime($dend) <= strtotime($dstart)){
            $data = array('success' => false,
                "message" => "Fecha de término no puede ser núla",
                "errors" => array("Error" => "Fecha de término no puede ser menor o igual a la fecha la de inicio")
                );
            $this->layout->printLike(json_encode($data), "json");
            return;
        }

        //fechas no puede ser menor a la actual
        if(strtotime($dstart) < strtotime(date("Y-m-d"))){
            $data = array('success' => false,
                "message" => "Fecha de término no puede ser núla",
                "errors" => array("Error" => "Fecha de inicio no puede ser menor que la fecha actual")
                );
            $this->layout->printLike(json_encode($data), "json");
            return;
        }
        //obtenemnos objeto
        $object = $this->objects_model->getByid($objects_id);
        if(empty($object[0])){
            $data = array(
                'success' => false,
                "message" => "El objeto [$objects_id] no existe",
                "errors" => array("Error" => "El objeto [$objects_id] no existe")
            );
            $this->layout->printLike(json_encode($data), "json");
            return;
        }
        $object = $object[0];

        //obtenemos el tipo objeto
        $typeObject = $this->type_objects_model->getByid($object->type_objects_id);
        if(!empty($typeObject[0])){
            $_moduleName = $typeObject[0]->name;
        }

        //validamos que exista modulo
        $module = $this->modules_model->getByid($modules_id);
        if(empty($module[0])){
            $data = array(
                'success' => false,
                "message" => "El modulo [$module] no existe",
                "errors" => array("Error" => "El Modulo [$module] no existe")
            );
            $this->layout->printLike(json_encode($data), "json");
            return;
        }
        $module = $module[0];

        $this->db->trans_begin();

        //JSON con configuracion de inscripcion de objeto con modulo
        $config = new stdClass();
        $config->start = $dstart;
        $config->end = $dend;
        $config->test = new stdClass();
        if($selected == "true"){
            $config->test->random = 0;
            $config->test->selectedQuestions = $selectedQuestions;
        }
        else{
            $config->test->random = 1;
            $config->test->nQuestions = $nQuestions;   
        }

        $config->test->minCorrectAnswers = $minCorrectAnswers;
        $config->test->repetitions = $repetitions;


        $data = array(
            "id" => array(
                "objects_id"=>$objects_id,
                "modules_id"=>$modules_id
            ),
            "data" => array(
                'objectversion' => $object->version,
                "config"=> htmlspecialchars( json_encode($config) ),
            )
        );
        
        if (!$this->modules_objects_model->save($data, true)) {
            $data = array(
                'success' => false,
                "message" => "Proceso fallo al momento de editar objeto con modulo [$modules_id] del Grupo [$groups_id]",
                "errors" => array("Error" => $this->modules_objects_model->getError())
            );
            $this->db->trans_rollback();
            $this->layout->printLike(json_encode($data), "json");        
            return;
        } 
        else{
            $this->db->trans_commit();
        }
        $data = array(
            'success' => true,
            "message" => "Inscripción exitosa",
            "errors" => array(),
        );
        $this->layout->printLike(json_encode($data), "json");
    }
    public function unregisterObject(){
        $this->load->model("role_group_model");
        $this->load->model("objects_model");
        $this->load->model("modules_model");
        $this->load->model("modules_objects_model");

        $success = false;
        $itemName = $this->role_group_model->getItemName();
        $mensaje = "Error inesperado";
        $errorList = array();
        
        $groups_id = $this->input->post('groups_id');
        $objects_id = $this->input->post('objects_id');

        //obtenemnos objeto
        $object = $this->objects_model->getByid($objects_id);
        if(empty($object[0])){
            $data = array(
                'success' => false,
                "message" => "El objeto [$objects_id] no existe",
                "errors" => array("Error" => "El objeto [$objects_id] no existe")
            );
            $this->layout->printLike(json_encode($data), "json");
            return;
        }
        $object = $object[0];
        //validamos que grupo posea modulo de tipo asociado al objeto
        $modules = $this->modules_model->getBygroups_id($groups_id);
        $module = null;
        foreach ($modules as $m) {
            if($m->type_objects_id == $object->type_objects_id){
                $module = $m;
                break;
            }
        }
        if($module==null){
            log_message("error","(unregisterObject) No se encuentra modulo asociado a grupo $groups_id de tipo object $object->type_objects_id");
            $data = array(
                'success' => false,
                "message" => "El objeto [$objects_id] no existe",
                "errors" => array("Error" => "El objeto [$objects_id] no esta inscrito en el modulo asociado a este grupo")
            );
            $this->layout->printLike(json_encode($data), "json");
            return;
        }

        $data = array(
            'objects_id'=>$objects_id,
            'modules_id'=>$module->id,
        );
        
        if ($this->modules_objects_model->del($data, true)) {
            $mensaje = "Inscripcion eliminado en forma existosa";
            $success = true;
        } else {
            $mensaje = "El objeto no puedo ser eliminado. Verifique los siguientes errores.";
            $errorList = array("Error" => $this->modules_objects_model->getError());
        }
        $data = array(
            'success' => $success,
            "msg" => $mensaje,
            "errors" => $errorList,
        );
        $this->layout->printLike(json_encode($data), "json");
    }
    public function getSubscribedObject(){
        $this->load->model("role_group_model");
        $this->load->model("objects_model");
        $this->load->model("modules_model");
        $this->load->model("modules_objects_model");
        $this->load->model("type_objects_model");
        $this->load->model("groups_model");
        $this->load->model("elem_test_model");

        $cfg = (object)$this->config->item('defaultCfg');
        
        $errorList = array();
        
        $objects_id = $this->input->post('objects_id');
        $modules_id = $this->input->post('modules_id');
        $groups_id = $this->input->post('groups_id');

        //obtengo module object
        $query = new stdClass();
        $query->conditions = new stdClass();
        $query->conditions->objects_id = $objects_id;
        $query->conditions->modules_id = $modules_id;
        $query->single = true;

        $module_object = $this->modules_objects_model->listEntities($query);

        if(empty($module_object["items"])){
            $data = array(
                'success' => false,
                "errors" => array("Error" => "No existe la relacion entre el objeto y el modulo asociado al grupo consultado."),
            );
            $this->layout->printLike(json_encode($data), "json");
        }

        $module = $this->modules_model->getByid($modules_id);
        $object = $this->objects_model->getByid($objects_id);
        $group = $this->groups_model->getByid($groups_id);



        //no existe modulo
        if(empty($module[0])){
            $data = array(
                'success' => false,
                "msg" => $mensaje,
                "errors" => array("Error" => "No existe un modulo para el objeto en el grupo consultado."),
            );
            $this->layout->printLike(json_encode($data), "json");
            return;
        }
        //no existe modulo
        if(empty($object[0])){
            $data = array(
                'success' => false,
                "errors" => array("Error" => "No existe el objeto consultado."),
            );
            $this->layout->printLike(json_encode($data), "json");
            return;
        }
        //no existe grupo
        if(empty($group[0])){
            $data = array(
                'success' => false,
                "errors" => array("Error" => "No existe el grupo consultado."),
            );
            $this->layout->printLike(json_encode($data), "json");
            return;
        }

        

        $module_object = $module_object["items"][0];
        $module_object->config = str_replace("&quot;", '"', $module_object->config);
        $module_object->config = json_decode($module_object->config);

        //print_r($module_object);exit;

        $module = $module[0];
        $object = $object[0];
        $group = $group[0];

        //obtenemos test del objeto
        $test = $this->elem_test_model->getByobjects_id($objects_id);
        if(!empty($test[0])){
            $module->test_id = $test[0]->id;
        }


        $module->groupname = $group->name;
        $module->groups_id = $group->id;
        $module->modules_id = $module->id;
        $module->type_objects_id = $object->type_objects_id;
        $module->category_id = $object->category_id;
        $module->dstart = $module_object->config->start;
        $module->dend = $module_object->config->end;
        $module->objects_id = $object->id;

        if(!empty($module_object->config->test->nQuestions))
            $module->nQuestions = $module_object->config->test->nQuestions;

        if(!empty($module_object->config->test->selectedQuestions))
            $module->selectedQuestions = $module_object->config->test->selectedQuestions;

        if(!empty($module_object->config->test->repetitions))
            $module->repetitions = $module_object->config->test->repetitions;

        if(!empty($module_object->config->test->minCorrectAnswers))
            $module->minCorrectAnswers = $module_object->config->test->minCorrectAnswers;
        
        $data = array(
            'success' => true,
            "data" => $module
        );
        $this->layout->printLike(json_encode($data), "json");
    }
    public function loadGrid() {
        $cfg = $this->config->item('defaultCfg');

        $options = new stdClass();
        $options->conditions = new stdClass();
        $options->start = $this->input->get('start');
        $options->limit = $this->input->get('limit');
        $options->conditions->deleted = $this->input->get('deleted');

        if (!$this->input->get('sort')) {
            $options->orderField = 'id';
            $options->orderDirection = 'DESC';
        } else {
            $orden = $this->input->get('sort');
            $sort = json_decode($orden);
            $options->orderField = $sort[0]->property;
            $options->orderDirection = $sort[0]->direction;
        }

        $data = $this->_modelInstance->listEntities($options);
        //$data = $this->_modelInstance->loadListCrud($options);

        //me evito una nueva query sql :D

        $res = array(
            "success" => true,
            "results" => $data['results'],
            "sql" => $data['sql'],
            "rows" => $data['items']
        );
        $this->layout->printLike(json_encode($res), "json");
    }
    public function get(){
        $id = $this->input->post('id');
        $object = $this->_modelInstance->getByid($id);
        if(!empty($object[0]))
            $object = $object[0];
        $res = array(
            "success" => true,
            "data" => $object
        );
        $this->layout->printLike(json_encode($res), "json");
    }
    public function add(){
        $cfg = (object)$this->config->item('defaultCfg');
        $valid = true;
        $success = false;
        $itemName = $this->_modelInstance->getItemName();
        $mensaje = $itemName . " creado en forma exitosa";
        $errorList = array();
        
        $name = $this->input->post('name');
        $description = $this->input->post('description');
        $typegroups_id = $this->input->post('typegroups_id');
        $uid = $this->session->userdata('id_usuario');
        $userEmail = $this->session->userdata('uid');
        
        $this->form_validation->set_rules($this->_modelInstance->getValidations());
        $_id = 0;
        $_object = null;

        if ($this->form_validation->run() == FALSE) {
            $mensaje = "Campos inválidos";
            $errorList = $this->form_validation->_error_array;
        } else {
            $description = str_replace("'", "", $description);
            $name = str_replace("'", "", $name);
            $data = array(
                "id" => "",
                "data" => array(
                    'ucreated'=>$userEmail,
                    'name'=>$name,
                    'description' => $description,
                    "typegroups_id" => $typegroups_id
                )
            );
            
            if ($this->_modelInstance->save($data, false)) {
                $success = true;
            } else {
                $mensaje = "El objeto no pudo ser creado. Verifique los siguientes errores.";
                $errorList = array("Error" => $this->_modelInstance->getError());
            }
        }
        $data = array(
            'success' => $success,
            "msg" => $mensaje,
            "errors" => $errorList,
        );
        $this->layout->printLike(json_encode($data), "json");
    }
    public function edit(){
        $cfg = (object)$this->config->item('defaultCfg');
        $valid = true;
        $success = false;
        $itemName = $this->_modelInstance->getItemName();
        $mensaje = $itemName . " editado en forma exitosa";
        $errorList = array();
        
        $id = $this->input->post('id');
        $name = $this->input->post('name');
        $description = $this->input->post('description');
        $status = $this->input->post('status');
        $uid = $this->session->userdata('id_usuario');
        $userEmail = $this->session->userdata('uid');
        
        $this->form_validation->set_rules($this->_modelInstance->getValidations());
        $_id = 0;
        $_object = null;

        if ($this->form_validation->run() == FALSE) {
            $mensaje = "Campos inválidos";
            $errorList = $this->form_validation->_error_array;
        } else {
            $description = str_replace("'", "", $description);
            $name = str_replace("'", "", $name);
            $data = array(
                "id" => array(
                    'id'=>$id
                ),
                "data" => array(
                    'umodified'=>$userEmail,
                    "dmodified"=>date('Y-m-d H:i:s'),
                    'name'=>$name,
                    'status'=>$status,
                    'description' => $description
                )
            );
            
            if ($this->_modelInstance->save($data, true)) {
                $success = true;
            } else {
                $mensaje = "El objeto no pudo ser creado. Verifique los siguientes errores.";
                $errorList = array("Error" => $this->_modelInstance->getError());
            }
        }
        $data = array(
            'success' => $success,
            "msg" => $mensaje,
            "errors" => $errorList,
        );
        $this->layout->printLike(json_encode($data), "json");
    }
    public function del(){
        $success = false;
        $itemName = $this->_modelInstance->getItemName();
        $mensaje = "Error inesperado";
        $errorList = array();
        
        $id = $this->input->post('id');
        $object = $this->_modelInstance->getByid($id);
      
        
        if(is_array($object)) $object = $object[0];
        
        if(!empty($object)){
            $data = array(
                "id" => array(
                    'id'=>$id
                ),
                "data" => array(
                    'deleted'=>1
                )
            );
            
            if ($this->_modelInstance->save($data, true)) {
                $mensaje = "Centro eliminado en forma existosa";
                $success = true;
            } else {
                $mensaje = "El objeto no puedo ser eliminado. Verifique los siguientes errores.";
                $errorList = array("Error" => $this->_modelInstance->getError());
            }
        }
        $data = array(
            'success' => $success,
            "msg" => $mensaje,
            "errors" => $errorList,
        );
        $this->layout->printLike(json_encode($data), "json");
    }
}